package com.jdjw.utils;

import com.alibaba.fastjson.JSON;
import com.jdjw.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * java请求接口
 * @author kuangwl
 * @version 1.0
 * @description: TODO
 * @date 2021/5/31 10:12 上午
 */
@Slf4j
public class HttpRequestUtil {
    private static boolean debug = true;

    //get请求
    public static String sendGet(String url, String param) {
        if (!debug) {
            return "";
        }
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);

            URLConnection connection = realUrl.openConnection();

            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            connection.connect();

            Map<String, List<String>> map = connection.getHeaderFields();

            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }

            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("异常" + e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * [post请求]
     * @param url（远程请求的URL）
     * @param param（远程请求参数）
     * @return 远程请求返回的
     */
    public static String sendPost(String url, String param) {
        if (!debug) {
            return "";
        }
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流（设置请求编码为UTF-8）
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            System.out.println("sendPost"+result);
        } catch (Exception e) {
            System.out.println("异常" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static JSONObject getHttpResponseJson(String url,Map<String,String> param){

        CloseableHttpClient httpclient = null;
        CloseableHttpResponse response = null;
        JSONObject jsonObject = null;

        try {
            //请求发起客户端
            httpclient = HttpClients.createDefault();
            //参数集合
            List postParams = new ArrayList();
            //遍历参数并添加到集合
            for(Map.Entry<String, String> entry:param.entrySet()){
                postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            //通过post方式访问
            HttpPost post = new HttpPost(url);
            HttpEntity paramEntity = new UrlEncodedFormEntity(postParams,"UTF-8");
            post.setEntity(paramEntity);
            response = httpclient.execute(post);
            HttpEntity valueEntity = response.getEntity();
            String content = EntityUtils.toString(valueEntity);
            jsonObject = JSONObject.fromObject(content);
            return jsonObject;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return jsonObject;
    }


    /**
     * HttpEntity发送post请求（相信全部证书）
     * @param url
     * @param list
     * @return
     */
    public static JSONObject getHttpResponseJsonAllSSL(String url, ArrayList list) {
        JSONObject jsonObject = null;
        // 响应模型
        CloseableHttpResponse response = null;
        HttpEntity responseEntity = null;
        ResponseResult stuCode = null;

        SSLContextBuilder con = null;
        CloseableHttpClient httpClient = null;
        try {
            con = new SSLContextBuilder().loadTrustMaterial(null, (x, y) -> true);
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(con.build());
            HttpClientBuilder builder = HttpClients.custom();
            builder.setSSLSocketFactory(factory);
            httpClient =builder.build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);

        StringEntity entity = new StringEntity(JSON.toJSONString(list), "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            responseEntity = response.getEntity();

            if (responseEntity != null) {
                String content = EntityUtils.toString(responseEntity);
                jsonObject = JSONObject.fromObject(content);
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("http发送post数据失败");
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.info("失败: IOException");
            }
        }
        return jsonObject;
    }


    /**
     * HttpEntity发送post请求（相信全部证书）-字符串待遇特殊字符
     * @param url
     * @param list
     * @return
     */
    public static JSONObject getHttpResponseJsonAllSSLTS(String url, ArrayList list) {
        JSONObject jsonObject = null;
        // 响应模型
        CloseableHttpResponse response = null;
        HttpEntity responseEntity = null;
        ResponseResult stuCode = null;

        SSLContextBuilder con = null;
        CloseableHttpClient httpClient = null;
        try {
            con = new SSLContextBuilder().loadTrustMaterial(null, (x, y) -> true);
            SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(con.build());
            HttpClientBuilder builder = HttpClients.custom();
            builder.setSSLSocketFactory(factory);
            httpClient =builder.build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        String json = CommonUtil.objectToString(list);
        StringEntity entity = new StringEntity(json, "UTF-8");

        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);

        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            responseEntity = response.getEntity();

            if (responseEntity != null) {
                String content = EntityUtils.toString(responseEntity);
                jsonObject = JSONObject.fromObject(content);
                return jsonObject;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("http发送post数据失败");
        } finally {
            try {
                // 释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.info("失败: IOException");
            }
        }
        return jsonObject;
    }
}
